﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using PPI.Client;
using PPI.Client.Logic;
using PPI.Client.Logic.Inspection;
using PPI.Client.Presenter;
using PPI.Client.Utils;
using PPI.Entities;
using PPI.Entities.Inspections;
using PPI.Entities.Lookup;
using PPI.Entities.XML;
using PPI.General;
using VMind.Global;

namespace PPI.CRUD
{
    public partial class frmInspectionCRUD : frmBase, IInspectionCRUD
    {
        private List<EHandheld> m_Handhelds;
        private List<EXMissionStructures_TopType> m_TopTypes;
        private List<EXMissionStructures_PoleClass> m_Classes;
        private List<EXMissionStructures_PoleSpecies> m_Species;
        private List<EXMissionStructures_PoleTreatment> m_Treatments;
        private List<EMap> m_Maps;
        private List<ESection> m_Sections;
        private List<ECompany> m_Companies;
        private List<EInspector> m_Inspectors;
        private List<ENote> m_notes;
        private List<EInspectionTypes> m_InspectionTypes;
        private List<EResultType> m_resultTypes;
        private EXmlOutboxBase m_OutboxBase;
        private InspectionCRUDPresenter m_Presenter;
        private EInspection m_Inspection;
        private List<EInspectionImage> m_DeletedImages;
        private List<EVendor_Visit_Type> m_VisitTypes;


        #region Properties
        public EXmlOutboxBase Database
        {
            get { return m_OutboxBase; }
            set { m_OutboxBase = value; }
        }

        public EInspection Inspection
        {
            get { return m_Inspection; }
            set { m_Inspection = value; }
        }

        #endregion

        #region Events
        
        private void ddlMap_SelectedIndexChanged(object sender, EventArgs e)
        {
            try
            {
                if (ddlMap.SelectedIndex > 0)
                {
                    CheckComboIndex();
                }
            }
            catch (Exception ex)
            {
                RegisterError.SaveError(ex);
            }
        }

        private void ddlCompany_SelectedIndexChanged(object sender, EventArgs e)
        {
            try
            {
                if (ddlCompany.SelectedIndex > 0)
                {
                    ListBoxItem _selectedItem = (ListBoxItem)ddlCompany.SelectedItem;
                    m_Inspectors = m_Companies.Find(delegate(ECompany c) { return c.Id == ConvertHelper.ToInt32(_selectedItem.Value); }).Inspectors;
                    DropdownHelper.FillDropDown(ddlInspector, m_Inspectors, typeof(EInspector), "Name", "Id", "Select an option...");
                    if (m_Inspection != null)
                        ddlInspector.SelectedIndex = DropdownHelper.GetItemIndex(ddlInspector, m_Inspection.Inspector.Id.ToString());
                    CheckComboIndex();
                }
            }
            catch (Exception ex)
            {
                RegisterError.SaveError(ex);
            }
            

        }

        private void frmInspectionCRUD_Load(object sender, EventArgs e)
        {
            try
            {
                m_DeletedImages = new List<EInspectionImage>();
                if (m_Inspection != null)
                {
                    ResetComboIndex();
                    ResetValues();
                    LoadResultData();
                    LoadInspectionData();
                    LoadImages();
                    CheckComboIndex();
                }
            }
            catch (Exception ex)
            {
                RegisterError.SaveError(ex);
            }
        }

        private void lstImages_SelectedIndexChanged(object sender, EventArgs e)
        {
            try
            {
                if (lstImages.SelectedIndex > -1)
                {
                    EInspectionImage tmpImage = (EInspectionImage)lstImages.SelectedItem;
                    viewImage(tmpImage);

                }
            }
            catch (Exception ex)
            {
                RegisterError.SaveError(ex);
            }
        }

        private void lstImages_KeyDown(object sender, KeyEventArgs e)
        {
            try
            {
                if (e.KeyCode == Keys.Delete)
                {
                    if (lstImages.SelectedIndex > -1)
                    {
                        EInspectionImage tmpImage = (EInspectionImage)lstImages.SelectedItem;
                        m_DeletedImages.Add(tmpImage);
                        m_Inspection.Images.Remove(tmpImage);
                        LoadImages();
                    }

                }
            }
            catch (Exception ex)
            {
                RegisterError.SaveError(ex);
            }
        }

        private void btnSearchImage_Click(object sender, EventArgs e)
        {
            SearchImage();
        }

        private void btnSave_Click(object sender, EventArgs e)
        {
            if (Save())
            {
                this.DialogResult = DialogResult.OK;
                this.Close();
            }
                

        }

        private void btnClose_Click(object sender, EventArgs e)
        {
            this.Close();
        }


        #endregion

        public frmInspectionCRUD()
        {
            InitializeComponent();

            base.MenuMain.Visible = false;

            this.FormSize = FormSizes.Large;

            try
            {
                m_Presenter = new InspectionCRUDPresenter(this);

                LoadCombos();
            }
            catch (Exception ex)
            {
                RegisterError.SaveError(ex);
            }

        }

        private void LoadCombos()
        {
            m_Classes = LCacheDataSingleton.Instance.Class;
            DropdownHelper.FillDropDown(ddlClass, m_Classes, typeof(EXMissionStructures_PoleClass), "Name", "Id", "Select an option...");

            m_Species = LCacheDataSingleton.Instance.Specie;
            DropdownHelper.FillDropDown(ddlSpecie, m_Species, typeof(EXMissionStructures_PoleSpecies), "Name", "Id", "Select an option...");

            m_Treatments = LCacheDataSingleton.Instance.Treatment;
            DropdownHelper.FillDropDown(ddlTreatment, m_Treatments, typeof(EXMissionStructures_PoleTreatment), "Name", "Id", "Select an option...");

            DataTable dtLength = FillSpecificDataTableHelper.FillDataTable(35, 95, 5);
            DropdownHelper.FillDropDown(ddlLength, dtLength, "Name", "Id", "Select an option...");

            DataTable dtYears = FillSpecificDataTableHelper.FillDataTable(1944, DateTime.Now.Year, 1);
            DropdownHelper.FillDropDown(ddlYear, dtYears, "Name", "Id", "Select an option...");

            DataTable dtSections = FillSpecificDataTableHelper.FillDataTable(1, 36, 1);
            DropdownHelper.FillDropDown(ddlSection, dtSections, "Name", "Id", "1 to 36");

            m_TopTypes = LCacheDataSingleton.Instance.TopTypes;
            DropdownHelper.FillDropDown(ddlToptype, m_TopTypes, typeof(EXMissionStructures_TopType), "Name", "XMissionStructures_TopTypeId", "Select an option...");

            m_Companies = LCacheDataSingleton.Instance.Companies;
            DropdownHelper.FillDropDown(ddlCompany, m_Companies, typeof(ECompany), "Name", "Id", "Select an option...");

            m_notes = LCacheDataSingleton.Instance.Notes;
            DropdownHelper.FillListBox(lstNotes, m_notes, typeof(ENote), "Name", "Id","");

            m_InspectionTypes = LCacheDataSingleton.Instance.InspectionTypes;
            DropdownHelper.FillDropDown(ddlInspectionType, m_InspectionTypes, typeof(EInspectionTypes), "Name", "Id", "Select an option...");

            m_resultTypes = LCacheDataSingleton.Instance.ResultTypes;
            DropdownHelper.FillDropDown(ddlResultType, m_resultTypes, typeof(EResultType), "Name", "Id", "Select an option...");

            m_Maps = LCacheDataSingleton.Instance.Maps;
            DropdownHelper.FillDropDown(ddlMap, m_Maps, typeof(EMap), "Name", "Id", "Select an option...");

            m_VisitTypes = LCacheDataSingleton.Instance.VisitTypes;
            DropdownHelper.FillDropDown(ddlKv, m_VisitTypes, typeof(EVendor_Visit_Type), "Name", "Vendor_Visit_TypeId", "Select an option...");
        }

        private void CheckComboIndex()
        {
            DropdownHelper.CheckComboIndex(ddlClass);
            DropdownHelper.CheckComboIndex(ddlCompany);
            DropdownHelper.CheckComboIndex(ddlInspectionType);
            DropdownHelper.CheckComboIndex(ddlInspector);
            DropdownHelper.CheckComboIndex(ddlLength);
            DropdownHelper.CheckComboIndex(ddlMap);
            DropdownHelper.CheckComboIndex(ddlResultType);
            DropdownHelper.CheckComboIndex(ddlSection);
            DropdownHelper.CheckComboIndex(ddlSpecie);
            DropdownHelper.CheckComboIndex(ddlToptype);
            DropdownHelper.CheckComboIndex(ddlTreatment);
            DropdownHelper.CheckComboIndex(ddlYear);
            DropdownHelper.CheckComboIndex(ddlKv);
        }

        private void ResetComboIndex()
        {
            DropdownHelper.ResetComboIndex(ddlClass);
            DropdownHelper.ResetComboIndex(ddlCompany);
            DropdownHelper.ResetComboIndex(ddlInspectionType);
            DropdownHelper.ResetComboIndex(ddlInspector);
            DropdownHelper.ResetComboIndex(ddlLength);
            DropdownHelper.ResetComboIndex(ddlMap);
            DropdownHelper.ResetComboIndex(ddlResultType);
            DropdownHelper.ResetComboIndex(ddlSection);
            DropdownHelper.ResetComboIndex(ddlSpecie);
            DropdownHelper.ResetComboIndex(ddlToptype);
            DropdownHelper.ResetComboIndex(ddlTreatment);
            DropdownHelper.ResetComboIndex(ddlYear);
            DropdownHelper.ResetComboIndex(ddlKv);
        }

        private void LoadImages()
        {
            lstImages.DataSource = null;
            lstImages.Items.Clear();

            lstImages.DataSource = m_Inspection.Images;
            lstImages.DisplayMember = "Title";
        }

        private void LoadInspectionData()
        {
            try
            {
                position1.SetPosition(m_Inspection);

                if (m_Inspection.Class.Id != Int32.MinValue)
                    ddlClass.SelectedIndex = DropdownHelper.GetItemIndex(ddlClass, m_Inspection.Class.Id.ToString());

                if (m_Inspection.Company.Id != Int32.MinValue)
                    ddlCompany.SelectedIndex = DropdownHelper.GetItemIndex(ddlCompany, m_Inspection.Company.Id.ToString());

                if (m_Inspection.Length != Int32.MinValue)
                    ddlLength.SelectedIndex = DropdownHelper.GetItemIndex(ddlLength, m_Inspection.Length.ToString());

                if (m_Inspection.Map.Id != Int32.MinValue)
                    ddlMap.SelectedIndex = DropdownHelper.GetItemIndex(ddlMap, m_Inspection.Map.Id.ToString());

                if (m_Inspection.Specie.Id != Int32.MinValue)
                    ddlSpecie.SelectedIndex = DropdownHelper.GetItemIndex(ddlSpecie, m_Inspection.Specie.Id.ToString());

                if (m_Inspection.TopType.XMissionStructures_TopTypeId != Int32.MinValue)
                    ddlToptype.SelectedIndex = DropdownHelper.GetItemIndex(ddlResultType, m_Inspection.TopType.XMissionStructures_TopTypeId.ToString());

                if (m_Inspection.Treatment.Id != Int32.MinValue)
                    ddlTreatment.SelectedIndex = DropdownHelper.GetItemIndex(ddlResultType, m_Inspection.Treatment.Id.ToString());

                if (m_Inspection.Year != Int32.MinValue)
                    ddlYear.SelectedIndex = DropdownHelper.GetItemIndex(ddlYear, m_Inspection.Year.ToString());
                
                if (m_Inspection.Section.Id != Int32.MinValue)
                    ddlSection.SelectedIndex =DropdownHelper.GetItemIndex(ddlSection, m_Inspection.Section.Id.ToString());

                if (m_Inspection.VendorVisitType != null && m_Inspection.VendorVisitType.Vendor_Visit_TypeId != Int32.MinValue)
                    ddlKv.SelectedIndex = DropdownHelper.GetItemIndex(ddlKv, m_Inspection.VendorVisitType.Vendor_Visit_TypeId.ToString());

                dateLVisit.Value = m_Inspection.LastVisit;
                txtNumber.Text = m_Inspection.Number;
                txtLastInspector.Text = m_Inspection.LastCompanyName;
            }
            catch (Exception ex)
            {
                RegisterError.SaveError(ex);
            }
        }

        private void LoadResultData()
        {
            try
            {
                if (m_Inspection.Result.Id != Int32.MinValue)
                    ddlResultType.SelectedIndex = DropdownHelper.GetItemIndex(ddlResultType, m_Inspection.Result.Resultype.Id.ToString());

                if (m_Inspection.Result.InspectionType.Id != Int32.MinValue)
                    ddlInspectionType.SelectedIndex = DropdownHelper.GetItemIndex(ddlInspectionType, m_Inspection.Result.InspectionType.Id.ToString());

                txtComments.Text = m_Inspection.Result.Comments;
                chkIsElectrical.Checked = m_Inspection.Result.IsElectrical;
                SetSelectedNotes(m_Inspection.Result.Notes);
            }
            catch (Exception ex)
            {
                RegisterError.SaveError(ex);
            }

        }

        private void viewImage(EInspectionImage image)
        {
            if (image.ImageFile.Exists)
            {
                Bitmap _Bitmap = new Bitmap(image.ImageFile.FullName);
                pbxSelectedImage.Image = _Bitmap;
            }
        }

        private bool ValidateInspection()
        {
            bool returnValue = position1.ValidatePosition();

            if (!returnValue)
                tabMain.SelectedTab = tabInspection;
            return returnValue;
        }

        private bool validateResult()
        {
            return true;
        }

        private void SaveInspectionData()
        {
            position1.GetPosition(m_Inspection);
            ListBoxItem _selectedItem = null;

            #region Specie
            if (ddlSpecie.SelectedIndex > 0)
            {
                _selectedItem = (ListBoxItem)ddlSpecie.SelectedItem;
                m_Inspection.Specie = new EXMissionStructures_PoleSpecies(ConvertHelper.ToInt32(_selectedItem.Value), _selectedItem.Text);
            }
            else
                m_Inspection.Specie = new EXMissionStructures_PoleSpecies();

            #endregion

            #region Class
            if (ddlClass.SelectedIndex > 0)
            {
                _selectedItem = (ListBoxItem)ddlClass.SelectedItem;
                m_Inspection.Class = new EXMissionStructures_PoleClass(ConvertHelper.ToInt32(_selectedItem.Value), _selectedItem.Text);
            }
            else
                m_Inspection.Class = new EXMissionStructures_PoleClass();

            #endregion

            #region Treatment
            if (ddlTreatment.SelectedIndex > 0)
            {
                _selectedItem = (ListBoxItem)ddlTreatment.SelectedItem;
                m_Inspection.Treatment = new EXMissionStructures_PoleTreatment(ConvertHelper.ToInt32(_selectedItem.Value), _selectedItem.Text);
            }
            else
                m_Inspection.Treatment = new EXMissionStructures_PoleTreatment();

            #endregion

            if (ddlToptype.SelectedIndex > 0)
            {
                _selectedItem = (ListBoxItem)ddlToptype.SelectedItem;
                m_Inspection.TopType = new EXMissionStructures_TopType(ConvertHelper.ToInt32(_selectedItem.Value), _selectedItem.Text);
            }

            #region Year
            if (ddlYear.SelectedIndex > 0)
            {
                _selectedItem = (ListBoxItem)ddlYear.SelectedItem;
                m_Inspection.Year = ConvertHelper.ToInt32(_selectedItem.Value);
            }
            else
                m_Inspection.Year = Int32.MinValue;

            #endregion            

            #region Length
            if (ddlLength.SelectedIndex > 0)
            {
                _selectedItem = (ListBoxItem)ddlLength.SelectedItem;
                m_Inspection.Length = ConvertHelper.ToInt32(_selectedItem.Value);
            }
            else
                m_Inspection.Length = Int32.MinValue;
            
            #endregion

            #region Map
            if (ddlMap.SelectedIndex > 0)
            {
                _selectedItem = (ListBoxItem)ddlMap.SelectedItem;
                m_Inspection.Map = new EMap(ConvertHelper.ToInt32(_selectedItem.Value), _selectedItem.Text);
            }
            else
                m_Inspection.Map = new EMap(); 
            #endregion

            #region Section
            if (ddlSection.SelectedIndex > 0)
            {
                _selectedItem = (ListBoxItem)ddlSection.SelectedItem;
                m_Inspection.Section = new ESection(ConvertHelper.ToInt32(_selectedItem.Value),_selectedItem.Text);
            }
            else
                m_Inspection.Section = new ESection();
            #endregion

            if (ddlCompany.SelectedIndex > 0)
            {
                _selectedItem = (ListBoxItem)ddlCompany.SelectedItem;
                m_Inspection.Company = new ECompany(ConvertHelper.ToInt32(_selectedItem.Value), _selectedItem.Text);
            }
            if (ddlInspector.SelectedIndex > 0)
            {
                _selectedItem = (ListBoxItem)ddlInspector.SelectedItem;
                m_Inspection.Inspector = new EInspector(ConvertHelper.ToInt32(_selectedItem.Value), _selectedItem.Text);
            }
            if (ddlKv.SelectedIndex > 0)
            {
                _selectedItem = (ListBoxItem) ddlKv.SelectedItem;
                m_Inspection.VendorVisitType = new EVendor_Visit_Type(ConvertHelper.ToInt32(_selectedItem.Value), _selectedItem.Text);
            }

            m_Inspection.Number = txtNumber.Text;
            m_Inspection.LastCompanyName = txtLastInspector.Text.Trim();
            m_Inspection.LastVisit = dateLVisit.Value;
            m_Inspection.Project = this.Inspection.Project;
            m_Inspection.Contact = this.Inspection.Contact;
            m_Inspection.Structure = this.Inspection.Structure;
            m_Inspection.GuardsQuantity = Inspection.GuardsQuantity;
            
        }

        private void SaveResultData()
        {
            ListBoxItem _selectedItem = null;

            if (ddlInspectionType.SelectedIndex > 0)
            {
                _selectedItem = (ListBoxItem)ddlInspectionType.SelectedItem;
                m_Inspection.Result.InspectionType = new EInspectionTypes(ConvertHelper.ToInt32(_selectedItem.Value), _selectedItem.Text);
            }

            if (ddlResultType.SelectedIndex > 0)
            {
                _selectedItem = (ListBoxItem)ddlResultType.SelectedItem;
                m_Inspection.Result.Resultype = new EResultType(ConvertHelper.ToInt32(_selectedItem.Value), _selectedItem.Text);
            }
            m_Inspection.Result.Comments = txtComments.Text;
            m_Inspection.Result.IsElectrical = chkIsElectrical.Checked;
            m_Inspection.Result.Notes = GetSelectedNotes();
        }

        private List<ENote> GetSelectedNotes()
        {
            List<ENote> notes = new List<ENote>();
            foreach (ListBoxItem i in lstNotes.SelectedItems)
            {
                ENote note = new ENote(ConvertHelper.ToInt32(i.Value),i.Text);
                notes.Add(note);
            }
            return notes;
        }

        private void SetSelectedNotes(List<ENote> notes)
        {
            foreach (ENote note in notes)
            {
                int index = DropdownHelper.GetItemIndex(lstNotes, note.Id.ToString());
                if(index > -1)
                    lstNotes.SetSelected(index,true);
            }

        }

        private bool Save()
        {
            try
            {
                if (ValidateInspection() && validateResult())
                {
                    this.Cursor = Cursors.WaitCursor;
                    SaveResultData();
                    SaveInspectionData();
                    m_Presenter.SaveInspectionResult(m_Inspection, m_DeletedImages, m_OutboxBase.ConnectionString);
                    this.Cursor = Cursors.Default;
                    return true;
                }
                else
                    return false;
            }
            catch (Exception ex)
            {
                RegisterError.SaveError(ex);
                return false;
            }
        }

        private void SearchImage()
        {
            try
            {
                OpenFileDialog _OpenFileDialog = new OpenFileDialog();
                DialogResult _DialogResult = _OpenFileDialog.ShowDialog();
                EInspectionImage _Image;
                FileInfo _SelectedFile;
                switch (_DialogResult)
                {
                    case DialogResult.OK:
                    case DialogResult.Yes:
                        _SelectedFile = new FileInfo(_OpenFileDialog.FileName);
                        _Image = new EInspectionImage();
                        _Image.ImageFile = _SelectedFile;
                        _Image.InspectionResult = m_Inspection.Result;
                        _Image.Inspection = m_Inspection;
                        m_Inspection.Images.Add(_Image);
                        LoadImages();
                        break;
                    default:
                        break;
                }
            }
            catch (Exception ex)
            {
                RegisterError.SaveError(ex);
            }
        }

        private void ResetValues()
        {
            ResetComboIndex();
            txtComments.Text = string.Empty;
            txtLastInspector.Text = string.Empty;
            chkIsElectrical.Checked = false;
            CleanSeletedNotes();
        }

        private void CleanSeletedNotes()
        {
            for (int i = 0; i < lstNotes.Items.Count; i++ )
            {
                Int32 index = DropdownHelper.GetItemIndex(lstNotes, ((ListBoxItem)lstNotes.Items[i]).Value);
                if (index > -1)
                    lstNotes.SetSelected(index, false);
            }
        }

        private void CleanImageResource()
        {
            pbxSelectedImage.Image = null;
        }

        private void frmInspectionCRUD_FormClosing(object sender, FormClosingEventArgs e)
        {
            CleanImageResource();
        }
    }
}
